const Koa = require('koa');
const app = new Koa();
const route = require('koa-route');
const cors = require('koa2-cors');
const image2base64 = require('image-to-base64');
const hello = async ctx => {
  let fileUrl = ctx.request.query.url;
  if (!fileUrl) {
    ctx.body = data = {
      success:false,
      msg:'缺少资源地址'
    }
    return;
  }
  let imgUrl = decodeURIComponent(ctx.request.query.url)
  var data  = await new Promise((resolve,reject)=> {
    image2base64(imgUrl) // you can also to use url
    .then((response) => {
      resolve(response)
    })
    .catch((error) => {
      reject(imgUrl)
      console.log(error); //Exepection error....
    })
  })
  ctx.body = data;
};
app.use(cors({
  origin: function () {
    return "*";
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

app.use(route.get('/getQiniuImg', hello));
app.listen(8444);